'use client'

import { useEffect, useState } from 'react'
import i18next from 'i18next'
import { initReactI18next, useTranslation as useTranslationOrg } from 'react-i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import { getOptions, detectBrowserLanguage } from './setting'

// localStorage key for language storage
const LANGUAGE_STORAGE_KEY = 'i18next-language'
// 
i18next
  .use(initReactI18next)
  .use(resourcesToBackend((language: string, namespace: string) => import(`./locales/${language}/${namespace}.json`)))
  .init({
    ...getOptions(),
    lng: undefined, // let detect the language on client side
  })

export function useTranslation(ns: string = 'common', options?: any) {
    const ret = useTranslationOrg(ns, options)
    const { i18n } = ret

    // 获取localStorage中的语言设置
    const getStoredLanguage = () => {
        if (typeof window === 'undefined') return null;
        try {
            return localStorage.getItem(LANGUAGE_STORAGE_KEY);
        } catch (error) {
            console.warn('Failed to read language from localStorage:', error);
            return null;
        }
    }

    // 保存语言设置到localStorage
    const setStoredLanguage = (language: string) => {
        if (typeof window === 'undefined') return;
        try {
            localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
        } catch (error) {
            console.warn('Failed to save language to localStorage:', error);
        }
    }

    const changeLanguage = (language: string) => {
        i18n.changeLanguage(language);
        setStoredLanguage(language);
    }
    
    useEffect(() => {
        const browserLang = detectBrowserLanguage();
        const storedLang = getStoredLanguage();
        
        const initialLang = storedLang || browserLang;
        
        i18n.changeLanguage(initialLang);
        
        if (!storedLang) {
            setStoredLanguage(initialLang);
        }
    }, [i18n])
    
    return {...ret, changeLanguage };
}